<?php

namespace App\Services;
use App\Helpers\WXBizDataCrypt;
use App\Models\WxUsers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Helpers\ExcelHelper;
use Dingo\Api\Http\Middleware\Request;
use App\Models\cocloud\Organizations;
use Tymon\JWTAuth\Facades\JWTFactory;

class WxLoginService
{

    private static $appid = "wxd46e7c95a833a0b1";
    private static $AppSecret = "efed99d5b0c373513d622cb55ade5aa9";

    private static $sessionKey = "";

    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;

    /**
     * @param $request
     * @return string
     * @name 小程序登录处理
     * @user IHammer
     */
    public static function wxLoginHandle($request,&$errmsg){
        /**
         * 采集数据
         * */
        $wx_code = $request->get("wx_code");
        $wx_encrypted_data = $request->get("wx_encrypted_data");
        $wx_iv = $request->get("wx_iv");
        if(empty($wx_code)||empty($wx_encrypted_data)||empty($wx_iv)){
            $errmsg = "参数错误";
            return false;
        }
        /**
         * 处理数据
         */
        $session_data = self::getSessionData($wx_code);
        $session_data = json_decode($session_data, true);

        $openid = $session_data['openid']; //openid
        self::$sessionKey = $session_data['session_key'];//session_key

        //检查用户是否已经已经存在
        $wx_info = WxUsers::getInfo(['openid'=>$openid]);
        $token = "";
        if($wx_info){
            $token = encrypt(['openid'=>$openid]);
            @WxUsers::where(['openid'=>$openid])->update(['token'=>$token]);
            return ['token'=>$token];
        }else{
            $errCode = self::decryptData($wx_encrypted_data, $wx_iv,$data);  //其中$data包含用户的所有数据
            $data = json_decode($data);
            if ($errCode == 0) {
                $token = encrypt(['openid'=>$data->openId]);
                $insert_data['openid'] = $data->openId;
                $insert_data['nickname'] = $data->nickName;
                $insert_data['gender'] = $data->gender;
                $insert_data['city'] = $data->city;
                $insert_data['language'] = $data->language;
                $insert_data['province'] = $data->province;
                $insert_data['country'] = $data->country;
                $insert_data['avatarurl'] = $data->avatarUrl;
                $insert_data['token'] = $token;
                @WxUsers::create($insert_data);
                return ['token'=>$token];
            } else {
                $errmsg = "登录失败";
                return false;
            }
        }
    }
    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public static function decryptData($encryptedData, $iv, &$data ){
        if (strlen(self::$sessionKey) != 24) {
            return self::$IllegalAesKey;
        }
        $aesKey=base64_decode(self::$sessionKey);
        if (strlen($iv) != 24) {
            return self::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return self::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != self::$appid)
        {
            return self::$IllegalBuffer;
        }
        $data = $result;
        return self::$OK;

    }

    /**
     * @param $code
     * @return mixed
     * @name 获取SessionData
     * @user IHammer
     */
    public static function getSessionData($code){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . self::$appid . "&secret=" . self::$AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        return self::vget($url);  // 一个使用curl实现的get方法请求
    }
    public static function vget($url){
        $info=curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output= curl_exec($info);
        curl_close($info);
        return $output;
    }
}